<template>
  <div style="padding: 15px;">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" prop="warehouseCode" style="margin-right:15px" label-width="120px">
              <warehouseSelect ref="warehouseSelect"  @setWarehouseCode="setWarehouseCode" style="width: 100%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="盘点类型" style="margin-right:15px"  label-width="120px" prop="type">
              <el-select v-model="form.type"
                         @change="selectCountingType(form.type)"
                         placeholder="请选择盘点类型" style="width:100%" clearable>
                <el-option
                  v-for="item in countingTypeData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div v-if="showShipment" :key="1" class="grid-content bg-purple">
            <el-form-item label="入驻商" style="margin-right:15px"  label-width="120px" prop="shipmentCode">
              <shipmentSelect3 ref="shipmentSelect3"  @setShipmentInfo="setShipmentInfo" style="width: 100%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div v-if="showLocation" class="grid-content bg-purple">
            <el-form-item label="库位" style="margin-right:15px"  label-width="120px" prop="location">
              <el-autocomplete
                style="width:100%"
                :debounce="500"
                :trigger-on-focus="false"
                v-model="form.location"
                value-key="serialNumber"
                placeholder="请输入库位号"
                :fetch-suggestions="findLocations"
                @select="selectLocation"
              ></el-autocomplete>
              <!-- <el-select v-model="form.location"
                         @change="selectLocation(form.location)"
                         placeholder="请选择库位" style="width:100%">
                <el-option
                  v-for="item in locationData"
                  :key="item.code"
                  :label="item.serialNumber"
                  :value="item.code"
                />
              </el-select> -->
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div v-if="showOpQuantity" class="grid-content bg-purple">
            <el-form-item label="动碰次数" style="margin-right:15px"  label-width="120px" prop="opQuantity">
              <el-input v-model="form.opQuantity" type="number" min="0" max="99999999" step="1"  placeholder="请输入动碰次数" style="width:100%" @blur="blurOpQuantity"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="监盘人" style="margin-right:15px"  label-width="120px" prop="supervisor">
              <el-input v-model="form.supervisor" placeholder="请输入监盘人" style="width:100%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" style="margin-right:15px"  label-width="120px">
              <el-input v-model="form.remarks" placeholder="请输入备注" style="width:100%"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      ref="xTable"
      border
      resizable
      show-overflow
      row-id="id"
      height="500"
      :align="allAlign"
      :loading="loading"
      :data="tableData"
    >
      <template v-slot:empty>
        <p> 暂无数据！</p>
      </template>
      <vxe-table-column type="index" width="60" fixed="left" />
      <vxe-table-column field="warehouseSpaceName" title="库区" min-width="100" />
      <vxe-table-column field="locationName" title="库位" min-width="100"/>
      <vxe-table-column field="shipmentName" title="入驻商" min-width="100" />
      <vxe-table-column field="goodsName" title="商品名称" min-width="100" />
      <vxe-table-column field="goodCode" title="商品编码" min-width="100" />
      <vxe-table-column field="goodsBarCode" title="商品条码" min-width="100" />
      <vxe-table-column field="unitName" title="单位" min-width="100" />
      <vxe-table-column field="quantity" title="库存数量" min-width="100" />
      <vxe-table-column field="gmtManufacture" title="生产日期" min-width="150" />
      <vxe-table-column field="gmtExpire" title="过期日期" min-width="150" />
      <vxe-table-column field="gmtStock" title="存货日期" min-width="150" />
      <vxe-table-column field="receiveLot" title="收货批次" min-width="100" />
      <vxe-table-column field="goodsStatusName" title="库存状态" min-width="100" />
      <vxe-table-column field="isLock" title="锁定状态" min-width="100" :formatter="formatterLock" />
      <vxe-table-column field="supplier" title="供应商" width="120"/>
      <vxe-table-column field="serialNumber" title="序列号" width="120"/>
      <vxe-table-column field="extendOne" title="生产批号" width="120"/>
      <vxe-table-column field="extendTwo" title="商品批次" width="120"/>
      <vxe-table-column field="extendThree" title="扩展3" width="120"/>
      <vxe-table-column field="extendFour" title="扩展4" width="120"/>
      <vxe-table-column field="extendFive" title="扩展5" width="120"/>
      <vxe-table-column field="extendSix" title="扩展6" width="120"/>

    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmit" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import request from '@/utils/request'
  import { countingAdd, countingSubmit } from '@/api/store'

  import shipmentSelect3 from '@/views/components/shipmentSelect3.vue'
  import warehouseSelect from '@/views/components/warehouseSelect.vue'

  Vue.use(VXETable)
  export default {
    components: {
      warehouseSelect,
      shipmentSelect3,
    },
    data() {
      return {
        allAlign:'center',
        isDisable:false,   //确定键显示按钮
        tableData: [],
        showShipment: false,
        showLocation: false,
        showOpQuantity: false,
        warehouseData:[],//仓库列表
        shipmentData:[],
        locationData:[],
        //盘点类型列表
        countingTypeData:[
          { code: "0", name: "全盘" },
          { code: "1",name: "入驻商盘点" },
          { code: "2",name: "库位盘点" },
          { code: "3",name: "动碰盘点" }
        ],
        form: {
          code:'',                                //数据标识 ,
          name:'',                                //库位名称 ,
          remarks:'',                             //备注 ,
          status:'',                              //状态 ,
          total:'',                               //总数 ,
          warehouseCode:'',                       //所属仓库
          supervisor: '',
          opQuantity: '',
          shipmentCode: '',
          location: '',
          type: '',
          countingItemList: []
        },
        loading: false,
        rules: {
          warehouseCode: [
            {required: true, message: '请选择仓库', trigger: 'blur'},
          ],
          type: [
            {required: true, message: '请选择盘点类型', trigger: 'blur'},
          ],
          shipmentCode: [
            {required: true, message: '请选择入驻商', trigger: 'blur'},
          ],
          location: [
            {required: true, message: '请选择库位', trigger: 'blur'},
          ],
          opQuantity: [
            {required: true, message: '请输入动碰次数', trigger: 'blur'},
          ],
          supervisor: [
            {required: true, message: '请输入监盘人', trigger: 'blur'},
          ]
        },
        paramsData: null,
        listQuery: {
          total: 0,
          pageNum: 1,
          pageSize: 10,
        },
      }
    },
    created() {

    },
    methods: {
      // 选择仓库
      setWarehouseCode(value){
        this.form.warehouseCode = value;
        this.form.shipmentCode = '';
        this.form.shipmentName = '';
        this.tableData = [];
        this.listQuery.total = 0
        this.form.type = '';
        this.showShipment = false;
        this.showLocation = false;
        this.showOpQuantity = false;
      },

      formatterLock({ cellValue, row }) {
        row.lock = row.lockName;
        if (cellValue === 0) {
          return '否'
        } else if (cellValue === 1) {
          return '是'
        }
      },
      // 重置
      reset(){
        this.$refs['form'].resetFields()
      },
      // 保存
      funcSave() {
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细数据')
        } else {
          this.form.countingItemList = this.$refs.xTable.tableData;
          this.form.status = '0';
          const data = JSON.parse(JSON.stringify(this.form));
          data.location = data.code
          data.code = ''
          this.$refs['form'].validate((valid) => {
            if (valid) {
              this.isDisable = true;
              countingAdd(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$emit('fatherAddMethod')
                this.isDisable = false
              }).then(() => {
                  this.$eventBus.$emit('refreshList')
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.push({
                    path: "/kngl/counting"
                  });
                }).catch(() => this.isDisable = false)
            } else {
              return false
            }
          })
        }
      },
      // 提交
      funcSubmit() {
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('无盘点明细数据')
        } else {
          this.form.countingItemList = this.$refs.xTable.tableData;
          this.form.status = '1';
          const data = JSON.parse(JSON.stringify(this.form));
          data.location = data.code
          data.code = ''
          this.$refs['form'].validate((valid) => {
            if (valid) {
              this.isDisable = true;
                countingSubmit(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$emit('fatherSubmitMethod')
                this.isDisable = false
              }).then(() => {
                  this.$eventBus.$emit('refreshList')
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.push({
                    path: "/kngl/counting"
                  });
                }).catch(() => this.isDisable = false)
            } else {
              return false
            }
          })
        }
      },
      // 取消
      funcCancel() {
        this.$emit('fatherCancelMethod', 'add')
      },
      blurOpQuantity() {
        if(!(/(^[1-9]\d*$)/.test(this.form.opQuantity))){
          this.$message.error('动碰次数必须是正整数');
          return;
        }
        let params = {
          'warehouseCode': this.form.warehouseCode,
          'actionNum': this.form.opQuantity
        };
        this.listInventory(params);
      },
      //选择盘点类型
      selectCountingType(val) {
        //  由于入驻商插件是if-show的，所以为了避免隐藏时未清空，所以在选择类型时清空它
        this.form.shipmentCode = '';
        this.form.shipmentName = '';
        if(!(this.form.warehouseCode)){
          this.$message.error('请先选择盘点仓库');
          this.form.type = '';
          return;
        }

        if(0 == val) {
          this.showShipment = false;
          this.showLocation = false;
          this.showOpQuantity = false;
          let params = {
            'warehouseCode': this.form.warehouseCode
          };
          this.tableData=[];
          this.listInventory(params);
        }
        if(1 == val) {
          this.showShipment = true;
          this.showLocation = false;
          this.showOpQuantity = false;
          this.tableData=[];
          this.$nextTick(()=>{
            // this.$refs.shipmentSelect3.init(this.form.warehouseCode);
          })
        }
        if(2 == val) {
          this.showLocation = true;
          this.showShipment = false;
          this.showOpQuantity = false;
          this.tableData=[];
          this.findLocations();
        }
        if(3 == val) {
          this.showOpQuantity = true;
          this.showShipment = false;
          this.showLocation = false;
          this.tableData=[];
        }
      },
      // 分页handle
      handlePageChange({ currentPage, pageSize }) {
        this.listQuery.pageNum = currentPage
        this.listQuery.pageSize = pageSize
        this.listInventory(this.paramsData, 'pageChange')
      },
      listInventory(data, pageChange) {
        if (!pageChange) {
          this.paramsData = data;
        }
        const paramsData = Object.assign(this.paramsData, this.listQuery)
        this.loading = true;
        this.isDisable=true;   //确定键显示按钮
        request({
          url: '/wms/counting/inventory',
          method: 'get',
          params: paramsData
        }).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
          this.loading = false
          this.isDisable=false;   //确定键显示按钮
        })
      },
      // 选择入驻商
      setShipmentInfo(info) {
        this.form.shipmentCode = info.partyCode;
        this.form.shipmentName = info.userName;
        this.$refs.warehouseSelect.init(this.form.shipmentCode)
        let params = {
          'warehouseCode': this.form.warehouseCode,
          'shipmentCode': this.form.shipmentCode,
        };
        this.listInventory(params);
      },
      //选择库位
      selectLocation({ code }) {
        this.form.code = code
        let params = {
          location: code,
          warehouseCode: this.form.warehouseCode
        };
        this.listInventory(params)
      },
      // 从服务端搜索库位数据
      findLocations(queryString, cb) {
        let params = {
          pageSize: 99,
          locationName: queryString,
          warehouseCode: this.form.warehouseCode
        }
        request({
          url: '/wms/location/chooseDataLimit',
          method: 'get',
          params: params
        }).then(response => {
          cb && cb(response.data.records)
          this.locationData = response.data
        })
      }
    }
  }
</script>
<style lang="scss" scoped >
  .dialog-footer {
    margin: 80px auto;
    width: 175px;
    // float: right;
  }
</style>
